package com.xhwl.centiotdata.suppliersystem.mettler;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.handler.weigh.WeighIntegrationFactory;
import com.xhwl.centiotdata.handler.weigh.WeighIntegrationHandler;
import com.xhwl.centiotdata.pojo.dto.weigh.WeighConfigDTO;
import com.xhwl.centiotdata.service.cent.IDeviceCentService;
import com.xhwl.common.dto.cent.device.DeviceDTO;
import com.xhwl.common.dto.cent.iotdata.mettler.WeighDTO;
import com.xhwl.common.enums.CategoryEnum;
import com.xhwl.common.enums.ProductEnum;
import com.xhwl.common.enums.device.DeviceOnlineStatusEnum;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.bind.DatatypeConverter;
import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.HashMap;

/**
 * 称重处理
 *
 * @author pengjunming
 * @description
 * @date 2022/10/11 17:33
 */
@Slf4j
@Service
public class WeighMettlerHandler extends WeighIntegrationHandler {

    @Autowired
    private IDeviceCentService deviceCentService;

    final String firstWeigh = "/datasnap/rest/TServerMethods1/Addweight";
    final String secondWeigh = "/datasnap/rest/TServerMethods1/Upweight";

    @Override
    public JSONObject weigh(WeighConfigDTO config, WeighDTO data) {
        String url;
        JSONObject result;
        JSONObject param = new JSONObject();
//        if (StringUtils.isEmpty(data.getBalanceid())) {
        url = config.getHost() + firstWeigh;
        param.put("plateNumber", data.getPlateNumber());
        param.put("transportOrderCode", data.getTransportOrderCode());
        param.put("po", data.getPo());
        /*param.put("truckId", data.getTruckId());*/
        param.put("commandId", data.getCommandId());
        param.put("weightType", data.getWeightType());
        result = put(url, param, config);
//        } else {
//            url = config.getHost() + secondWeigh;
//            param.put("balanceid", data.getBalanceid());
//            result = post(url, param);
//        }
        return result;
    }

    @Override
    public void pullWeighDevice(WeighConfigDTO config) {
        DeviceDTO deviceDTO = new DeviceDTO();
        deviceDTO.setProjectId(config.getProjectId());
        deviceDTO.setProductId(config.getProductId());
        deviceDTO.setCategoryId(config.getCategoryId());
        deviceDTO.setDeviceTypeId(config.getDeviceType());
        deviceDTO.setName(config.getWeighDeviceName());
        deviceDTO.setThirdDeviceId(config.getHost());
        deviceDTO.setOnlineStatus(DeviceOnlineStatusEnum.ONLINE.id);
        deviceCentService.asyncUpdateDevice(Collections.singletonList(deviceDTO));
    }

    private JSONObject put(String url, JSONObject param, WeighConfigDTO config) {
        String signStr = config.getLoginName() + ":" + config.getPassword();
        String encoding = "";
        try {
            encoding = DatatypeConverter.printBase64Binary(signStr.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            log.error("无法对地磅的用户密码的字节进行编码");
            throw new BusinessException("回调失败");
        }
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Authorization", "Basic " + encoding);
        String body = HttpRequest.put(url)
                .addHeaders(headers)
                .body(param.toString())
                .execute()
                .body();
        JSONObject object = JSON.parseObject(body);
        return object;
    }

    private JSONObject post(String url, JSONObject param) {
        String post = HttpUtil.post(url, JSONObject.toJSONString(param));
        return JSONObject.parseObject(post);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        WeighIntegrationFactory.register(ProductEnum.WEIGHBRIDGE.getId(), this);
    }

}
